
<template>
    <div>
        <div class="head-box">
            <h2>请选择或添加您的账本</h2>
            <p>开始您的记账之旅</p>
            <div class="add-box" @click="openInputName()">
                <img src="@/assets/managemoney/white-add-btn-icon.png">
            </div>
        </div>
        
         
        <template v-for="(item,key) in dataList">
            <div class="card-box" :key="key" @click="manageMoneyBookDetail(item.id)">
                <h3 >
                    {{item.title}}
                </h3>
                <p class="date">{{item.createTime.date.month + "月" + item.createTime.date.day + "日"}}</p>
                <table class="data">
                    <tr>
                        <td>总支出</td>
                        <td>总收入</td>
                    </tr>
                    <tr>
                        <td>{{item.nowMonthPayOut}}￥</td>
                        <td>{{item.nowMonthPutIn}}￥</td>
                    </tr>
                </table>

                <div class="into-btn">
                    进入账本<img src="@/assets/managemoney/into-icon.png">
                </div>
            </div>
        </template>
        <template v-if="dataList.length <= 0">
        <van-empty description="暂无账本数据">
            <van-button round type="info" class="bottom-button" @click="openInputName()">
                添加新帐本
            </van-button>
        </van-empty>
        </template>


        <van-popup
            v-model="isManageMoneyBookNameShow"
        
            round 
            position="bottom"
            :style="{ height: '25%' }"
        >
            
            <div class="popup-title-box">
                <button class="cancel-btn" @click="cancelSubmit()">取消</button>
                <span class="title-txt">请输入账本昵称</span>
                <button class="sure-btn" @click="sureSubmit">确定</button>
            </div>
        <van-field
                v-model="manageMoneyBookName"
                rows="2"
                autosize
                type="textarea"
                maxlength="20"
                placeholder="请输入账本昵称"
                show-word-limit
            />
        </van-popup>
    </div>
</template>
<script>
    import axios from 'axios';
    
    import wx from 'weixin-js-sdk';

    
    import 'vant/lib/index.css';
    import { Icon } from 'vant';
    import { Popup } from 'vant';
    import { Field,Toast,Button } from 'vant';
    
    import { Empty } from 'vant';

	import { mapState, mapActions } from 'vuex'
    export default {
        name: 'Login',
        
        components: {
          
            [Icon.name]: Icon,
            [Popup.name]: Popup,
            [Field.name]: Field,
            [Toast.name]: Toast,
            [Empty.name]: Empty,
            [Button.name]: Button,
        },
        data(){
            return{
                isManageMoneyBookNameShow:false,
                manageMoneyBookName:'',
                dataList:[]
            }
        },
		computed: mapState({
			application: state => state.application.systemInfo,
			userId: state => state.login.userId,
			loginInfo: state => state.login.loginInfo,
			isLogin: state => state.login.isLogin,
			wxInfo:state => state.login.wxInfo,
			redirectFullPath:state => state.login.redirectFullPath
		}),
        created: function () {
            this.getManageMoneyBookDataList();
            // this.wxLogin();
            this.jsSDKConfig();
        },
        methods: {
            cancelSubmit(){
                this.hideInputName();
            },
            sureSubmit(){
                var that = this;
                var userId = this.userId;
                console.log(this.userId);
                var data = {title:this.manageMoneyBookName,createUserId:userId}
                axios.post("/api/expenseBookInfo/save",data)
                .then(res=>{
                    console.log('res=>',res);     
                    if(res.data == "success"){
                        that.hideInputName();
                        that.getManageMoneyBookDataList();
                        Toast.success("账本添加成功");

                    } else{
                        Toast.fail(res.data.msg);
                    }
                })
            },
            openInputName(){
                this.isManageMoneyBookNameShow = true;
            },
            hideInputName(){
                this.isManageMoneyBookNameShow = false;
            },
            getManageMoneyBookDataList(){
                var that = this;
                 var userId = this.userId;
                    // 上面的请求也可以这样做
                axios.get('/api/expenseBookInfo/list/data?createUserId=' + userId)
                .then(function (response) {
                    console.log(response.data.rows);
                    that.dataList = response.data.rows;
                    
                })
                .catch(function (error) {
                    console.log(error);
                });
            },

            manageMoneyBookDetail(id){
                this.$router.push({query:{manageMoneyBookId:id},path:'/expense/book/detail'})
            },

            wxLogin:function(){
                var isLogin = window.localStorage.getItem('isLogin');
                var userInfo = window.localStorage.getItem('userInfo');
                var code = this.$route.query.code;
                //console.log(userInfo );
                if(parseInt(isLogin) == 1){
                    this.$router.push('Tool');
                }else{
                    code = this.$route.query.code;
                    if(code == '' || code == null){
                        this.getWxLoginUrl();
                    }else{
                        window.localStorage.setItem("code",code);
                        var wxUser = window.localStorage.getItem("wxUser");
                        if(wxUser == null || wxUser == ''){
                            this.getWxUser();
                        }
                        
                    }
                }
            },
            getWxLoginUrl(){
                var returnUrl = encodeURIComponent('http://www.hjieli.com/weixinapp/#/Login');
                //console.log(returnUrl);
                 // 上面的请求也可以这样做
                axios.get('/api/weixin/OAuth?returnUrl='+returnUrl)
                .then(function (response) {
                    window.location.href = response.data;
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
            getWxUser(){
                var code = window.localStorage.getItem("code");
                 // 上面的请求也可以这样做
                axios.get('/api/weixin/getWeixinUser?code='+code)
                .then(function (response) {
                    var wxUser = JSON.parse(response.data.data).weixinUser;
                    window.localStorage.setItem("wxUser",JSON.stringify(wxUser));
                    window.localStorage.setItem("openId",wxUser.openId);
                    console.log(JSON.stringify(wxUser));
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
            getEmailCode(){
                //验证邮箱是否正确
                if(this.form.email == ''){
                    this.$toast.error('邮箱不能为空');
                    return false;
                }else{
                    if(this.email(this.form.email) == false){
                        this.$toast.error('请填写正确的邮箱');
                    return false;
                    }
                }
                const loading = Loading({
                    text:'邮件发送中......'
                });
                var email = this.form.email;
                var wxUser = window.localStorage.getItem("wxUser");
                var openId = window.localStorage.getItem("openId");
                if(openId == '' || openId == undefined || openId == null || openId == 'null' || openId == 'undefined' || wxUser == '' || wxUser == 'null' ){
                    this.getWxLoginUrl();
                }
                var that = this;
                axios.get('/api/code/sendCodeUseLogin?'+ encodeURI(encodeURI("subject=登录验证码")) + ' &email='+email + ' &openId='+openId + "&" + encodeURI(encodeURI("wxUser="+wxUser)))
                .then(function (response) {
                    
                    setTimeout(() => {
                        loading.close();
                        
                        if(response.data.errorno != "200"){
                            that.$toast.error(response.data.msg);
                        }else{
                            that.isDisabled = 0;
                            that.setBtnText();
                        }
                        
                    }, 1000);
                })
                .catch(function (error) {
                    setTimeout(() => {
                        loading.close();
                            that.$toast.error(error);
                    }, 1000);
                });
                
            },
            bindWeixin(){
                //验证邮箱是否正确
                if(this.form.email == ''){
                    this.$toast.error('邮箱不能为空');
                    return false;
                }else{
                    if(this.email(this.form.email) == false){
                         this.$toast.error('请填写正确的邮箱');
                    return false;
                    }
                }
                //验证验证码是否为空
                if(this.form.emailCode == ''){
                    this.$toast.error('验证码不能为空');
                    return false;
                }
                const loading = Loading({
                    text:'账号登录中......'
                });
                var email = this.form.email;
                var emailCode = this.form.emailCode;
                var wxUser = window.localStorage.getItem("wxUser");

                var openId = JSON.parse(wxUser).openId;
                var that = this;
                axios.get('/api/login/useEmail?email='+email + ' &emailCode='+emailCode+ ' &openId='+openId )
                .then(function (response) {
                     setTimeout(() => {
                        loading.close();
                        var errorno = response.data.errorno;
                        if(errorno == "200"){
                            window.localStorage.setItem("userInfo",JSON.stringify(response.data.data));
                            window.localStorage.setItem("isLogin","1");
                            that.$router.push('Tool');
                        }else{
                            that.$toast.error(response.data.msg);
                        }
                    }, 500);
                   
                    
                })
                .catch(function (error) {
                     setTimeout(() => {
                        loading.close();
                            that.$toast.error(error);
                    }, 1000);
                });
                
            },
            jsSDKConfig(){
                var url = encodeURIComponent(window.location.href.split('#')[0]);
                this.axios.get('/api/weixin/getJsConfig?url='+url)
                .then(function (response) {
					var jsConfig = response.data.data;
					jsConfig = JSON.parse(jsConfig);
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: jsConfig.appId, // 必填，公众号的唯一标识
                        timestamp: jsConfig.timestamp, // 必填，生成签名的时间戳
                        nonceStr: jsConfig.nonceStr, // 必填，生成签名的随机串
                        signature: jsConfig.signature,// 必填，签名
                        jsApiList: ['hideAllNonBaseMenuItem','onMenuShareAppMessage','updateAppMessageShareData','showMenuItems'] // 必填，需要使用的JS接口列表
                    });
                    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                        wx.hideAllNonBaseMenuItem();
                        // wx.showMenuItems({
                        //     menuList: ['menuItem:share:appMessage','menuItem:share:timeline'] // 要显示的菜单项，所有menu项见附录3
                        // });
                        // wx.onMenuShareAppMessage({ 
                        //     title: '一路向北', // 分享标题
                        //     desc: '小功能', // 分享描述
                        //     link: encodeURIComponent(window.location.href.split('?')[0]), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        //     imgUrl: '', // 分享图标
                        //     type: '', // 分享类型,music、video或link，不填默认为link
                        //     dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        //     success: function () {
                        //     // 设置成功
                        //     }
                        // })
                    });
                    
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
            tips(){
                this.$alert(this.tipMsg, '提示', {
                    okLabel: '知道了'
                }).then(() => {
                    
                });
            },
            bindEmail(){
                var code = this.$route.query.code;
                if(code == '' || code == undefined){
                   this.$router.replace({path:'Bind',query:{'code':code}});
                }else{
                    this.$router.replace('Bind');
                }
                
            },
            email: function(value) {
                if (value == null || this.trim(value) == "") return true;
                return /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value);
            },
            trim(value) {
                return value.replace(/(^\s*)|(\s*$)/g, "");
            },
            setBtnText() {
                var that = this;
                if(that.loopTime == 0){
                    that.loopTime = 60;
                    that.isDisabled = 1;
                    that.btnText = '获取验证码';
                    return false;
                }else{
                    that.loopTime -- ;
                    that.btnText = that.loopTime + " 秒"; 
                }
                setTimeout(function() {  
                    that.setBtnText();
                }, 1000);
            }
        }
    }

</script>

<style scoped>
    .head-box{
        height: auto;
        overflow: hidden;
        padding: 16px;
        background-color: #3387FB;   
        color: white;
         font-family: '微软雅黑';
         position: relative;
    }

    .head-box p{
        font-size: 16px;
    }

    .card-box{
        margin: 16px;
        padding: 16px;
        border-radius: 10px;
        background-color: white;
        box-shadow: 1px 1px 5px 0px #e0e0e0;
        text-align: left;
        position: relative;
    }
    .card-box h3{
        margin: 0px;
    }

    .card-box .date{
        font-size: 16px;
        color: #dddddd;
        margin: 0px;
        padding: 8px 0px;
         font-family: '微软雅黑';
    }

    .card-box .data{
        width: 100%;
        text-align: center;
        font-size: 16px;
    }
   
   .card-box .into-btn{
       position: absolute;
       top: 16px;
       right: 16px;
       font-size: 18px;
       color: #3387FB;
        font-family: '微软雅黑';
   }
    
    .into-btn img{ height: 16px;}

    .add-box{
        margin: 8px;
        text-align: center;
        position: absolute;
        top: 0px;
        right: 0px;
    }
    .add-box img{
        width: 30px;
    }

    
    .popup-title-box{
        height: 56px;
            display: -webkit-box;
        display: -webkit-flex;
        display: flex;
        -webkit-box-align: center;
        -webkit-align-items: center;
        align-items: center;
        -webkit-box-pack: justify;
        -webkit-justify-content: space-between;
        justify-content: space-between;
    }

    .popup-title-box .title-txt{
        max-width: 50%;
        font-weight: 500;
        font-size: 16px;
        line-height: 20px;
        text-align: center;
    }

    .popup-title-box button{
        height: 100%;
        padding: 0 16px;
        font-size: 14px;
        background-color: transparent;
        border: none;
        cursor: pointer;
        
    }

    .popup-title-box .cancel-btn{
        color: #969799;
    }

    .popup-title-box .sure-btn{
        color: #576b95;
    }

    
    .van-empty{
        height: 500px;
        background-color: white;
    }
     .bottom-button {
        width: 160px;
        height: 40px;
    }
</style>